//
//  OrderFormViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/22.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "OrderFormViewController.h"
#import "ShareCell.h"
#import "OrderDetailViewController.h"
#import "DeliveryViewController.h"
#import "SDSendMaViewController.h"
#import "SubmitOrderViewController.h"

@interface OrderFormViewController ()<UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate, YFMenuViewDelegate>
{
    NSString *deal_type;
    UILabel *footLable;
    NSInteger page;
    YFMenuView *headerView;
}

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation OrderFormViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubViews];
    self.view.backgroundColor = kColors(255, 255, 255, 1);
    self.title = @"速降订单";
    deal_type = @"0";
    [self requestData];
    page = 1;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)requestData
{
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kDealListUrl];
    NSDictionary *diction = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_type":deal_type, @"page":[NSNumber numberWithInteger:page]};
    [NetworkHandle getUpDataWithUrl:string class:NSClassFromString(@"SendModel") dictionary:diction firstKey:@"data" secondKey:@"list" success:^(NSArray *array) {
        if (page == 1) {
            [self.dataArray removeAllObjects];
        }
        [self.dataArray addObjectsFromArray:array];
        if (self.dataArray.count == 0) {
            footLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 30)];
            footLable.text = @"您没有相关订单";
            footLable.textAlignment = NSTextAlignmentCenter;
            self.tableView.tableFooterView = footLable;
        } else {
            self.tableView.tableFooterView = nil;
            footLable = nil;
        }
        if (self.dataArray.count >= 10 && self.tableView.footer == nil) {
            self.tableView.frame = CGRectMake(0, 46, kScreenWidth,kScreenHeight);
            self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        }
        
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        [self.tableView reloadData];
    }];
}

- (void)addSubViews
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 46, kScreenWidth, kScreenHeight - 46) style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    headerView = [[YFMenuView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44) select:self.pushType];
    headerView.delegate = self;
    [self.view addSubview:headerView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ShareCell"bundle:nil] forCellReuseIdentifier:@"ShareCell"];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    

}

- (void)headerRefresh
{
    page = 1;
    [self requestData];
}

- (void)footerRefresh
{
    page++;
    [self requestData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArray.count > 0) {
        return self.dataArray.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 133;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SendModel *model = self.dataArray[indexPath.row];
    ShareCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShareCell" forIndexPath:indexPath];
    [cell.deleteBtn addTarget:self action:@selector(actionDeleteBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.deleteBtn.tag = 1000000 + indexPath.row;
    [cell.shareBtn addTarget:self action:@selector(actionShareBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.shaiBtn addTarget:self action:@selector(actionThirdBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    cell.shaiBtn.tag = 100000 + indexPath.row;
    cell.model = model;
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}

#pragma mark -- 按钮点击事件

- (void)changeMenuAtIndex:(NSInteger)index
{
    deal_type = [NSString stringWithFormat:@"%ld", index];
    page = 1;
    [self requestData];
    self.tableView.tableFooterView = nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SendModel *model = self.dataArray[indexPath.row];
    if (model.status.integerValue == 4) {
        DeliveryViewController *deliveryVC= [[DeliveryViewController alloc]init];
        deliveryVC.model = model;
        [self.navigationController pushViewController:deliveryVC animated:YES];
    } else {
        ShareCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc]init];
        [self.navigationController pushViewController:orderDetailVC animated:YES];
        orderDetailVC.model = model;
        orderDetailVC.remain_time = cell.leftTimeLb.text;
    }
}

- (void)actionThirdBtn:(UIButton *)button
{
    NSString *title = button.titleLabel.text;
    if ([title isEqualToString:@"再次购买"]) {
        [self.navigationController popToRootViewControllerAnimated:NO];
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        [app setRootVC];
    } else if ([title isEqualToString:@"立即付款"]){
        [self actionPayBtn:button];
    } else if ([title isEqualToString:@"提醒发货"] || [title isEqualToString:@"确认收货"]) {
        [self actionAcceptBtn:button];
    } else if ([title isEqualToString:@"晒!"]){
        [self actionShaiBtn:button];
    }
}

// 付款按钮
- (void)actionPayBtn:(UIButton *)button
{
    SubmitOrderViewController *subVC = [[SubmitOrderViewController alloc] initWithNibName:@"SubmitOrderViewController" bundle:nil];
    subVC.pushType = @"1";
    SendModel *model = self.dataArray[button.tag - 100000];
    ShareCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag - 100000 inSection:0]];
    model.remain_seconds = cell.leftTimeLb.text;
    subVC.sendModel = model;
    [self.navigationController pushViewController:subVC animated:YES];
}

//// 申请退款
//- (void)returnMoneyOrderIndex:(NSInteger)index
//{
//    SendModel *model = self.dataArray[index];
//    NSString *string = [NSString stringWithFormat:@"%@/user.do?cmd=refund", kBaseUrl];
//    NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_id":model.deal_id};
//    [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
//        if ([dictionary[@"code"] isEqualToString:@"200"]) {
//            [Tools showAlert:@"申请退款成功, 已退还到您的钱包!"];
//            [self.dataArray removeObject:model];
//            [self.tableView reloadData];
//        } else {
//            [Tools showAlert:dictionary[@"message"]];
//        }
//    }];
//}

// 确认收货
- (void)actionAcceptBtn:(UIButton *)button
{
    if ([button.titleLabel.text isEqualToString:@"提醒发货"]){
        [Tools showAlert:@"已提醒!"];
        return;
    }
    // /user.do?cmd=ensure_get&u=x&deal_id=XXXX
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=ensure_get"];
    SendModel *model = self.dataArray[button.tag - 100000];
    NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_id":model.deal_id};
    [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
        [self.tableView reloadData];
        [Tools showAlert:dictionary[@"message"]];
    }];
}

// 删除
- (void)actionDeleteBtn:(UIButton *)button
{
    if ([button.titleLabel.text isEqualToString:@"删除"]){
        [self deleteOrderIndex:button.tag - 1000000];}
//    } else if ([button.titleLabel.text isEqualToString:@"申请退款"]) {
//        [self returnMoneyOrderIndex:button.tag - 1000000];
//    }
}

- (void)deleteOrderIndex:(NSInteger)index
{
    SendModel *model = self.dataArray[index];
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=delete_deal"];
    NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_id":model.deal_id};
    [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
        
        if ([dictionary[@"code"] integerValue] == 200) {
            [Tools showAlert:@"删除成功!"];
            [self.dataArray removeObject:model];
        }else
        {
            
        }
        
        if (self.dataArray.count <10) {
            self.tableView.footer =nil;
        }
        [self.tableView reloadData];
        if (self.dataArray.count == 0) {
            footLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 30)];
            footLable.text = @"您没有相关订单";
            footLable.textAlignment = NSTextAlignmentCenter;
            self.tableView.tableFooterView = footLable;
        } else {
            self.tableView.tableFooterView = nil;
            footLable = nil;
        }
    }];

}

// 分享
- (void)actionShareBtn:(UIButton *)button
{
    NSString *contentText = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"share_word"]];
    [UMSocialData defaultData].extConfig.wechatSessionData.title =@"速降";
    [UMSocialData defaultData].extConfig.wechatTimelineData.title =@"速降";
    [UMSocialData defaultData].extConfig.qqData.title = @"速降";
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5699e81567e58e7cba000b92"
                                      shareText:contentText
                                     shareImage:[UIImage imageNamed:@"sujiang"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,nil]
                                       delegate:self];
}

-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据responseCode得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        // 分享成功返回积分!
        NSString *string = [NSString stringWithFormat:@"%@/user.do?cmd=share_integral", kBaseUrl];
        NSDictionary *dic = @{@"u":[[NSUserDefaults standardUserDefaults]objectForKey:@"user_id"]};
        [NetworkHandle getInfoWithUrl:string dictionary:dic success:^(NSDictionary *dictionary) {
            [Tools showAlert:@"恭喜您获得10分享积分!"];
        }];
    }
}

// 晒!
- (void)actionShaiBtn:(UIButton *)button
{
    SendModel *model = self.dataArray[button.tag - 100000];
    if (model.status.integerValue == 6) {
        [Tools showAlert:@"本单已晒过"];
        return;
    }
    SDSendMaViewController *sdSendMaVC = [[SDSendMaViewController alloc]init];
    [self.navigationController pushViewController:sdSendMaVC animated:YES];
    sdSendMaVC.name = model.name;
    sdSendMaVC.deal_id = model.deal_id;
    sdSendMaVC.price = model.buy_price;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
